/**
 * KAYO APPLIANCE CHAINS.
 * Copyright (c) 2016-2016 All Rights Reserved.
 */
package com.leku.mse.mq.listener.member;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.leku.commons.datasource.DataSourceContextHolder;
import com.leku.mse.constants.DataSourceConstant;
import com.leku.mse.dao.member.FavoriteDao;
import com.leku.mse.entity.FavoriteEntity;

/**
 * 功能描述:收藏数据同步监听
 *
 * @author suiying
 * @created 2017年5月31日
 * @version 1.0.0
 */
public class FavoriteSyncListener implements MessageListener {

    private static final Logger LOG = LoggerFactory.getLogger(FavoriteSyncListener.class);

    @Autowired
    private FavoriteDao favoriteDao;

    /*
     * (non-Javadoc)
     * @see javax.jms.MessageListener#onMessage(javax.jms.Message)
     */
    @Override
    public void onMessage(Message message) {
        FavoriteEntity favoriteEntity = null;
        String msg = null;
        try {
            TextMessage textMsg = (TextMessage) message;
            msg = textMsg.getText();
            LOG.info("收藏消息:" + msg);
            favoriteEntity = JSON.parseObject(msg, FavoriteEntity.class);
        } catch (Exception e) {
            LOG.error("同步收藏消息异常", msg);
        }

        if (favoriteEntity == null) {
            return;
        }

        // 设置为会员中心数据库
        DataSourceContextHolder.setDataSourceType(DataSourceConstant.memDataSource());

        if ("0".equals(favoriteEntity.getStatus())) {
            // 收藏
            favoriteDao.insertFavorite(favoriteEntity);
        } else if ("1".equals(favoriteEntity.getStatus())) {
            // 取消收藏
            favoriteDao.deleteFavorite(favoriteEntity.getMemberCode(), favoriteEntity.getRelaCode(),
                    favoriteEntity.getRelaType(), favoriteEntity.getAppCode());
        }
    }

}
